<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <!--
        <el-form-item prop="system" label="系统">
          <el-input v-model="listQuery.system" placeholder="系统" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="systemName" label="系统名称">
          <el-input v-model="listQuery.systemName" placeholder="系统名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="service" label="服务">
          <el-input v-model="listQuery.service" placeholder="服务" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="serviceName" label="服务名">
          <el-input v-model="listQuery.serviceName" placeholder="服务名" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="fileType" label="文件类型">
          <el-select v-model="listQuery.fileType" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('FileType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item prop="fileName" label="附件存储名称">
          <el-input v-model="listQuery.fileName" placeholder="附件存储名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="md5" label="附件MD5值">
          <el-input v-model="listQuery.md5" placeholder="附件MD5值" @keyup.enter="handleFilter" />
        </el-form-item>
        <!--
        <el-form-item prop="size" label="附件大小(字节)">
          <el-input v-model="listQuery.size" placeholder="附件大小(字节)" @keyup.enter="handleFilter" />
        </el-form-item>
        -->
        <el-form-item prop="uploader" label="附件上传人">
          <User v-model="listQuery.uploader" keyName="id" keyShow="name" placeholder="附件上传人" title="用户查询" :disabled="useUserStore().organization.organizationType !== '1'" />
        </el-form-item>
        <el-form-item prop="storage" label="附件存储方式">
          <el-input v-model="listQuery.storage" placeholder="附件存储方式" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="bucket" label="附件存储桶">
          <el-input v-model="listQuery.bucket" placeholder="附件存储桶" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="path" label="存储路径">
          <el-input v-model="listQuery.path" placeholder="存储路径" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="original" label="原始文件名">
          <el-input v-model="listQuery.original" placeholder="原始文件名" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="url" label="附件URL">
          <el-input v-model="listQuery.url" placeholder="附件URL" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Edit" @click="handleAdd">
            新增
          </el-button>
          -->
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="系统" prop="system" min-width="80px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="系统名称" prop="systemName" min-width="120px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="服务" prop="service" min-width="80px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="服务名" prop="serviceName" min-width="120px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="文件类型" prop="fileType" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <DictTag :dict-list="getDictList('FileType')" :dict-key="row.fileType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="附件存储名称" prop="fileName" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.fileName }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件MD5值" prop="md5" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.md5 }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件大小" prop="size" min-width="150px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ bytesToSize(row.size) }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件上传人" width="180px" prop="uploader" sortable show-overflow-tooltip>
        <template v-slot="{row}"><LabelTag :foreignList="userList" :foreign-ids="row.uploader" :foreign-label="'name'" /></template>
      </el-table-column>
      <el-table-column align="center" label="附件存储方式" prop="storage" min-width="140px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.storage }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件存储桶" prop="bucket" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.bucket }}</template>
      </el-table-column>
      <el-table-column align="center" label="存储路径" prop="path" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.path }}</template>
      </el-table-column>
      <el-table-column align="center" label="原始文件名" prop="original" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.original }}</template>
      </el-table-column>
      <el-table-column align="center" label="附件URL" prop="url" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.url }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <!--
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
          -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="系统" prop="system">
          <el-input v-model="obj.system" placeholder="请输入系统，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="obj.systemName" placeholder="请输入系统名称，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="服务" prop="service">
          <el-input v-model="obj.service" placeholder="请输入服务，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="服务名" prop="serviceName">
          <el-input v-model="obj.serviceName" placeholder="请输入服务名，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="obj.fileType" class="m-2" placeholder="请选择">
            <el-option key="" label="请选择" value="" />
            <el-option v-for="item in getDictList('FileType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item label="附件存储名称" prop="fileName">
          <el-input v-model="obj.fileName" placeholder="请输入附件存储名称，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="附件MD5值" prop="md5">
          <el-input v-model="obj.md5" placeholder="请输入附件MD5值，最多输入50个字符" />
        </el-form-item>
        <el-form-item label="附件大小(字节)" prop="size">
          <el-input v-model="obj.size" type="number" placeholder="请输入附件大小(字节)" />
        </el-form-item>
        <el-form-item label="附件存储方式" prop="storage">
          <el-input v-model="obj.storage" placeholder="请输入附件存储方式，最多输入20个字符" />
        </el-form-item>
        <el-form-item label="附件存储桶" prop="bucket">
          <el-input v-model="obj.bucket" placeholder="请输入附件存储桶，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="存储路径" prop="path">
          <el-input v-model="obj.path" placeholder="请输入存储路径，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="原始文件名" prop="original">
          <el-input v-model="obj.original" placeholder="请输入原始文件名，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="附件URL" prop="url">
          <el-input v-model="obj.url" placeholder="请输入附件URL，最多输入500个字符" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, bytesToSize, customValidator, getListPageSize, notifySuccess} from '@/config/common'
import useUserStore from "@/store/modules/user";
import {getUserId} from "@/config/cookie";
import User from "@/views/components/base/selectUser.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  system: 'icims', // 系统
  systemName: '内控信息管理', // 系统名称
  service: 'icims-api', // 服务
  serviceName: '接口服务', // 服务名
  fileType: null, // 文件类型
  fileName: null, // 附件存储名称
  md5: null, // 附件MD5值
  size: null, // 附件大小(字节)
  uploader: null, // 附件上传人
  storage: null, // 附件存储方式
  bucket: null, // 附件存储桶
  path: null, // 存储路径
  original: null, // 原始文件名
  url: null, // 附件URL
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'attachment',
  components: {User},
  mixins: [baseConfig],
  data() {
    const svc = 'icims-api'
    return {
      svc,
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        system: null,
        systemName: null,
        service: null,
        serviceName: null,
        fileType: null,
        fileName: null,
        md5: null,
        size: null,
        uploader: useUserStore().organization.organizationType !== '1' ? getUserId() : '',
        storage: null,
        bucket: null,
        path: null,
        original: null,
        url: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        system: [{ required: false, validator: customValidator, min: 0, max: 100, label: '系统', trigger: ['blur', 'change'] }],
        systemName: [{ required: false, validator: customValidator, min: 0, max: 100, label: '系统名称', trigger: ['blur', 'change'] }],
        service: [{ required: false, validator: customValidator, min: 0, max: 100, label: '服务', trigger: ['blur', 'change'] }],
        serviceName: [{ required: false, validator: customValidator, min: 0, max: 100, label: '服务名', trigger: ['blur', 'change'] }],
        fileType: [{ required: false, validator: customValidator, min: 0, max: 20, label: '文件类型', trigger: ['blur', 'change'] }],
        fileName: [{ required: false, validator: customValidator, min: 0, max: 200, label: '附件存储名称', trigger: ['blur', 'change'] }],
        md5: [{ required: false, validator: customValidator, min: 0, max: 50, label: '附件MD5值', trigger: ['blur', 'change'] }],
        size: [{ required: false, validator: customValidator, min: 0, max: 20, label: '附件大小(字节)', trigger: ['blur', 'change'] }],
        uploader: [{ required: false, validator: customValidator, min: 0, max: 20, label: '附件上传人', trigger: ['blur', 'change'] }],
        storage: [{ required: false, validator: customValidator, min: 0, max: 20, label: '附件存储方式', trigger: ['blur', 'change'] }],
        bucket: [{ required: false, validator: customValidator, min: 0, max: 100, label: '附件存储桶', trigger: ['blur', 'change'] }],
        path: [{ required: false, validator: customValidator, min: 0, max: 200, label: '存储路径', trigger: ['blur', 'change'] }],
        original: [{ required: false, validator: customValidator, min: 0, max: 200, label: '原始文件名', trigger: ['blur', 'change'] }],
        url: [{ required: false, validator: customValidator, min: 0, max: 500, label: '附件URL', trigger: ['blur', 'change'] }],
      },
      userList: initListStore().userList,
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'attachment'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    this.getList()
    // this.initList()
  },
  methods: {
    useUserStore,
    bytesToSize,
    // async initList() {
    //   let p1 = doGet(this.svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1])
    //   this.userList = resArray[0]['records']
    // },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/attachment/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/attachment/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, `/attachment/${row.id}`, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        this.dialogVisible = false
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      switch (this.dialogType) {
        case 'add':
          doPost(this.svc, '/attachment/add', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        case 'edit':
          doPut(this.svc, '/attachment/modify', this.obj).then(() => {
            notifySuccess('操作成功')
            this.getList()
            this.dialogVisible = false
          })
          break
      }
    },
  }
}
</script>
